import { AfterViewInit, Component, ContentChild, ElementRef, Input, ViewChild } from '@angular/core';
import {NgModel} from "@angular/forms";

@Component({
  selector: 'meta-input',
  template: `
    <nz-input-group [nzSuffix]="suffixTemplate" [ngStyle]="style">
      <span #content>
        <ng-content>
        </ng-content>
      </span>
    </nz-input-group>
    <ng-template #suffixTemplate
    ><i
      nz-icon
      nz-tooltip
      class="ant-input-clear-icon"
      nzTheme="fill"
      nzType="close-circle"
      *ngIf="content.firstChild.value && !disabled"
      (click)="onClear()"
    ></i
    ></ng-template>
  `
})
export class MetaInputComponent implements AfterViewInit {
  @Input() disabled: boolean = false;

  ngAfterViewInit(): void {
    let width = this.content.nativeElement.firstChild.offsetWidth;
    if (width) {
      this.style = {width: this.content.nativeElement.firstChild.offsetWidth + 'px'};
    }
  }

  @ContentChild(NgModel, {static: true}) input: NgModel;
  @ViewChild('content', {static: true}) content: ElementRef;
  style = {};

  onClear(): void {
    let control = this.input.control;
    control.setValue('');
    control.markAsDirty();
    control.updateValueAndValidity();
  }
}
